# -*- coding: utf-8 -*-
#Importamos funciones standars
import datetime
from django.db.models import Q
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.models import User

#Importamos modulos nuestros
from models import colores
from formularios import Fcolores
from mundofacu.foro.models import denuncias, threads, posts
from mundofacu.news.models import noticias, comentarios
from mundofacu.usuarios.formularios import Famonestacion, Ftipousuario
from mundofacu.usuarios.models import amonestaciones, mensajes
from mundofacu.usuarios.decoradores import login_required, under_construction, mod_required
from mundofacu.usuarios.models import perfil, amonestaciones, carreras
from mundofacu.usuarios.funciones import exist, save, mail_desactivacion

#Definimos nuestras vistas
def Vindex(request):
	return render_to_response('portal/index.html', {"title":"Portal general"}, context_instance=RequestContext(request))


@login_required
def Vchat(request):
	return render_to_response('portal/chat.html', {"title":"Portal general",'name':'ucse-seia'}, context_instance=RequestContext(request))

@login_required
def Vchatchannel(request,id):
	return render_to_response('portal/chat.html', {"title":"Portal general",'name':"ucse-"+carreras.objects.get(id=id).nombre}, context_instance=RequestContext(request))


def Vus(request):
	return render_to_response('portal/nosotros.html', {"title":"Portal general"}, context_instance=RequestContext(request))


def Vfaq(request):
	return render_to_response('portal/faq.html', {"title":"Portal general"}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vmod(request):
	return render_to_response('portal/mod.html', {"title":"Moderacion de usuarios"}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vmod_usrlist(request):
	return render_to_response('listado.html',{"title":"Usuarios", "lista":perfil.objects.all()}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vnegativos(request,tipo):
	if tipo=='1': tabla=perfil
	elif tipo=='2': tabla=threads
	elif tipo=='3': tabla=posts
	else: return render_to_response('error.html', {'title':"Moderacion elementos negativos", 'msg': 'No existe el elemento negativo que intenta acceder.'}, context_instance=RequestContext(request))
	return render_to_response('listado.html',{"title":"Listado de "+ tabla().__class__.__name__ + " negativos", "lista":tabla.objects.filter(puntaje__lt=0).all()}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vernegativo(request,tipo,id_foo):
	if tipo=='1': tabla=perfil
	elif tipo=='2': tabla=threads
	elif tipo=='3': tabla=posts
	else: return render_to_response('error.html', {'title':"Moderacion elementos negativos", 'msg': 'No existe el elemento negativo que intenta acceder.'}, context_instance=RequestContext(request))
	return render_to_response('portal/ver.html',{"title": tabla().__class__.__name__ + " negativos", 'elemento':tabla.objects.get(id=id_foo)}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vrestart(request,tipo,id_foo):
	if tipo=='1': tabla=perfil
	elif tipo=='2': tabla=threads
	elif tipo=='3': tabla=posts
	else: return render_to_response('error.html', {'title':"Restart puntaje de " + tabla().__class__.__name__, 'msg': 'No existe el elemento negativo que intenta volver a 0.'}, context_instance=RequestContext(request))
	r = tabla.objects.get(id=id_foo)
	r.puntaje= 0
	r.save()
	return render_to_response('save.html', {"title":"Restarting puntaje negativo","exito":True, "msg":"Puntaje reseteado", }, context_instance=RequestContext(request))


@login_required
@mod_required
def Vdenunciaslist(request):
	return render_to_response('portal/mod_list.html',{"title":"Denuncias sin revisar", "lista": denuncias.objects.filter(pendiente=True).all(),'lista2_nombre': 'Denuncias revisadas', 'lista2': denuncias.objects.filter(pendiente=False).all()}, context_instance=RequestContext(request))


@login_required
@mod_required
def Verdenuncia(request, id_foo):
	form = Famonestacion()
	if exist(denuncias,'id',id_foo):
		D= denuncias.objects.get(id=id_foo)
		D.pendiente= False
		save(D)
		if request.method == 'POST':
			if Famonestacion(request.POST).is_valid():
				x = D.raiz()
				if request.POST['estado'] == "0": mensajes(asunto="Advertencia desde moderacion",texto=request.POST['descripcion'], receptor=x.autor,emisor=request.user).save()
				else:
					A = amonestaciones(user=x.autor, autor=request.user, estado= request.POST['estado'],descripcion=request.POST['descripcion'])
					A.duracion(request.POST['dias'])
					A.asignar(x)
					mail_desactivacion(x.autor, A.estado, A.descripcion, A.hasta)
					A.save()
				return render_to_response('save.html', {"title":"Amonestacion","exito":True, "msg":"Amonestacion realizada", }, context_instance=RequestContext(request))
			else: form = Famonestacion(request.POST)
		return render_to_response('portal/ver_denuncia.html',{'title':'Denuncia','denuncia':D, 'form': form},context_instance=RequestContext(request))
	else: return render_to_response('error.html', {'title':"Moderacion de denuncias", 'msg': 'No existe la denuncia a la que intenta acceder.'}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vamonestaciones(request):
	return render_to_response('usuarios/amonestaciones.html',{"title":"Listado de amonestaciones vigentes", "lista":amonestaciones.objects.filter(hasta__gte=datetime.date.today()).all()}, context_instance=RequestContext(request))


@login_required
@mod_required
def Veramonestacion(request, id):
	return render_to_response('usuarios/amonestacion.html',{"title":"Amonestacion", "item":amonestaciones.objects.get(id=id)}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vcancelar_amonestacion(request, id):
	A = amonestaciones.objects.get(id=id)
	A.estado= "0"
	A.descripcion= A.descripcion + "(El moderador: " + request.user.username + ", ha dado de baja la amonestacion el dia: " + str(datetime.date.today()) +")"
	A.save()
	return render_to_response('save.html', {"title":"Amonestacion","exito":True, "msg":"Amonestacion cancelada", }, context_instance=RequestContext(request))


def Vsearch(request):
	if request.method == 'POST':
		searchlist= request.POST['search'].replace("!","").replace("?","").replace("+","").replace("-","").replace("*","").replace("(","").replace(")","").replace("$","").replace("%","").replace("/","").replace("\\","").split()
		nosearch= set(["a","e","y","o","u","la","el","ella","ellos","los","las","yo","tu","nosotros","un","desde","hasta","con","una"])
		searchlist= list(set(searchlist).difference(nosearch))
		resultados = set([])
		for w in searchlist:
			resultados|=(set(threads.objects.filter(Q(titulo__icontains=w) | Q(body__icontains=w)))
							| set(posts.objects.filter(body__icontains=w).all())
							| set(noticias.objects.filter(Q(titulo__icontains=w) | Q(body__icontains=w)))
							| set(comentarios.objects.filter(texto__icontains=w).all()))
		return render_to_response('portal/search.html', {"title":"Search", "result": resultados }, context_instance=RequestContext(request))
	else: return Vhacker(request)



@login_required
@mod_required
def Vamonestar(request,id):
	if exist(User,'id',id):
		if request.method == 'POST':
			if Famonestacion(request.POST).is_valid():
				if request.POST['estado'] == "0": mensajes(asunto="Advertencia desde moderacion",texto=request.POST['descripcion'], receptor=User.objects.get(id=id),emisor=request.user).save()
				else:
					A = amonestaciones(user=User.objects.get(id=id), autor=request.user, estado= request.POST['estado'],descripcion=request.POST['descripcion'])
					A.duracion(request.POST['dias'])
					mail_desactivacion(User.objects.get(id=id), A.estado, A.descripcion, A.hasta)
					A.save()
				return render_to_response('save.html', {"title":"Amonestacion","exito":True, "msg":"Amonestacion realizada", }, context_instance=RequestContext(request))
			else: return render_to_response('form.html', {"form": Famonestacion(request.POST),'title': "Amonestacion de usuario", }, context_instance=RequestContext(request))
		else: return render_to_response('form.html', {"form": Famonestacion(),'title': "Amonestacion de usuario", }, context_instance=RequestContext(request))
	else: return render_to_response('error.html', {'title':"Moderacion de Usuarios", 'msg': 'No existe el usuario al que intenta acceder.'}, context_instance=RequestContext(request))


@login_required
@mod_required
def Vcambiartipo(request,id):
	if exist(User,'id',id):
		if request.method == 'POST':
			if Ftipousuario(request.POST).is_valid():
				u= User.objects.get(id=id).get_profile()
				print u
				print u.tipo_usuario
				u.tipo_usuario= request.POST["tipo"]
				u.save()
				print u.tipo_usuario
				return render_to_response('save.html', {"title":"Cambiar el tipo de usuario","exito":True, "msg":"Cambio realizado", }, context_instance=RequestContext(request))
			else: return render_to_response('form.html', {"form": Ftipousuario(request.POST),'title': "Cambiar el tipo de usuario", }, context_instance=RequestContext(request))
		else: return render_to_response('form.html', {"form": Ftipousuario(),'title': "Cambiar el tipo de usuario", }, context_instance=RequestContext(request))
	else: return render_to_response('error.html', {'title':"Cambiar tipo de Usuarios", 'msg': 'No existe el usuario al que intenta acceder.'}, context_instance=RequestContext(request))


@login_required
def Vcolores(request):
	if request.method == 'POST':
		if Fcolores(request.POST).is_valid():
			print colores.objects.all()
			if exist(colores, "user", request.user.id):
				c = colores.objects.get(user=request.user)
				c.fondo= request.POST["fondo"]
				c.laterales= request.POST["laterales"]
				c.centro= request.POST["centro"]
				c.pie= request.POST["pie"]
			else: c = Fcolores(request.POST).save(commit=False)
			c.user= request.user
			c.save()
			return render_to_response('save.html', {"title":"Cambiar colores del sitio","exito":True, "msg":"Cambio realizado", }, context_instance=RequestContext(request))
		else: return render_to_response('form.html', {"form": Fcolores(request.POST),'title': "Cambiar colores del sitio",'cc':True }, context_instance=RequestContext(request))
	else: return render_to_response('form.html', {"form": Fcolores(),'title': "Cambiar colores del sitio",'cc':True }, context_instance=RequestContext(request))


@login_required
def Vcolores_default(request):
	if exist(colores, "user", request.user.id): colores.objects.get(user=request.user).delete()
	return render_to_response('save.html', {"title":"Colores del sitio","exito":True, "msg":"Cambio realizado", }, context_instance=RequestContext(request))

#Modulos de reporte de errores:
def Vunderconstruction(request):
	return render_to_response('not.html', {"tipo":1}, context_instance=RequestContext(request))
def Vloginrequired(request):
	return render_to_response('not.html', {"tipo":2}, context_instance=RequestContext(request))
def Vmodrequired(request):
		return render_to_response('not.html', {"tipo":3}, context_instance=RequestContext(request))
def Vstaffrequired(request):
		return render_to_response('not.html', {"tipo":4}, context_instance=RequestContext(request))
def Vhacker(request):
		return render_to_response('not.html', {"tipo":5}, context_instance=RequestContext(request))
def Vbanned(request):
		return render_to_response('not.html', {"tipo":6}, context_instance=RequestContext(request))
def Vsuspendido(request,fecha):
		return render_to_response('not.html', {"tipo":7,"fecha":fecha}, context_instance=RequestContext(request))
def Vmuted(request):
		return render_to_response('not.html', {"tipo":8}, context_instance=RequestContext(request))